package com.qf.juc;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author lixu
 */
public class HashMapSafeDemo {

    public static final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private HashMap hashMap = new HashMap();//把线程不安全改成安全的

    public static void main(String[] args) {

        //ConcurrentHashMap<Object, Object> chm = new ConcurrentHashMap<>();

        HashMapSafeDemo hashMapSafeDemo = new HashMapSafeDemo();


        //多线程
        for (int i = 0; i < 100 ; i++) {
            String k = String.valueOf(i);
            new Thread(()-> {
                //往Map添加数据
                hashMapSafeDemo.put(k,k);//线程不案例
                //查询Map
                System.out.println(hashMapSafeDemo.get(k));
            }, k + ":name").start();
        }
        //     java.util.ConcurrentModificationException
        //Concurrent:并发    Modification：修改    Exception  线程不安全


    }

    /**
     * 写操作
     * @param key
     * @param value
     */
    public void put(String key,String value){
        //加上锁
        ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
        writeLock.lock();//上了一把写锁
        //写操作
        hashMap.put(key,value);
        //解开锁
        writeLock.unlock();

    }
    /**
     * 读  操作
     * @param key
     */
    public Object get(String key){
        ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
        readLock.lock();
        Object value = hashMap.values();
        //hashMap.get(key)
        readLock.unlock();
        return value;
    }
}
